/**
 * My simple header template from child directory
 * ConcurrentIOCalculator.java - ${projectName} - ${organizationName} - ${inceptionYear}
 */
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 04.03.14
 * Time: 23:16
 * To change this template use File | Settings | File Templates.
 */
public class ConcurrentIOCalculator implements FileSizeCalculator {

    @Override
    public long calculateSize(String fileName) throws IOException {
        return new ForkJoinPool().invoke(new Counter(new File(fileName)));
    }

    private class Counter extends RecursiveTask<Long> {

        private File root;

        private Counter(File file) {
            this.root = file;
        }

        @Override
        protected Long compute() {
            if (root.isFile()) {
                return root.length();
            }
            List<Counter> subTasks = new ArrayList<Counter>();
            File[] filesInDirectory = root.listFiles();
            long size = 0;
            if (filesInDirectory != null && filesInDirectory.length != 0) {
                for (File file: filesInDirectory) {
                    Counter counter = new Counter(file);
                    counter.fork();
                    subTasks.add(counter);
                }
                for (Counter counter: subTasks) {
                    size += counter.join();
                }
                return size;
            }
            return 0L;
        }
    }

    @Override
    public String getName() {
        return "ConcurrentIOCalculator";
    }
}
